package net.shop.common;

import java.io.Serializable;
import java.util.Date;

import org.aopalliance.intercept.MethodInvocation;
import org.springmodules.cache.key.CacheKeyGenerator;

import ths.core.cache.CacheKeyProvider;

public class EntityCacheKeyGenerator implements CacheKeyGenerator  {

	public Serializable generateKey(MethodInvocation mi) {
		Object[] args = mi.getArguments();
		StringBuilder sb = new StringBuilder(mi.getMethod().getName());
		for (int i=0; args != null && i<args.length; i++) {
			sb.append(".");
			if (isPrimitive(args[i])) {
				sb.append(args[i].toString());
			} else {
				if (args[i] instanceof CacheKeyProvider) {
					sb.append(((CacheKeyProvider) args[i]).getCacheKey());
				} else {
					sb.append(String.valueOf(System.identityHashCode(args[i])));
				}
			}
		}
		return sb.toString();
	}
	
	protected boolean isPrimitive(Object arg) {
		return arg.getClass().isPrimitive() || arg.getClass().isEnum() ||
			arg instanceof Number || arg instanceof CharSequence ||
			arg instanceof Byte || arg instanceof Character ||
			arg instanceof Boolean || arg instanceof Date;
	}
}
